package com.yiibai.netty.stream.demo1.client;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TimeClientHandler extends ChannelInboundHandlerAdapter{

	private ByteBuf buf;
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf m = (ByteBuf)msg;
		buf.writeBytes(m);
		m.release();
		
		if(buf.readableBytes() >= 4) {
			long currentTimeMills = (buf.readUnsignedInt() - 2208988800L) * 1000L;
			System.out.println(new Date(currentTimeMills));
			ctx.close();
		}
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		buf = ctx.alloc().buffer(4);  // ChannelHandler有两个生命周期侦听器方法：handlerAdded()和handlerRemoved()。 只要不会阻塞很长时间，您就可以执行任意初始化任务
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		buf.release();  // ChannelHandler有两个生命周期侦听器方法：handlerAdded()和handlerRemoved()。 只要不会阻塞很长时间，您就可以执行任意初始化任务
		buf = null;
	}

}
